package com.linxs.topcham.application.task.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.kissme.core.orm.Page;
import com.linxs.topcham.application.task.MonthCountService;
import com.linxs.topcham.domain.fans.Order;
import com.linxs.topcham.domain.org.AgencyOrg;
import com.linxs.topcham.domain.task.TaskOrg;
import com.linxs.topcham.infrastruture.persist.org.AgencyOrgRepository;
import com.linxs.topcham.infrastruture.persist.task.OrderRepository;
import com.linxs.topcham.infrastruture.persist.task.TaskRepository;

@Service
public class MonthCountServiceImpl implements MonthCountService {

	@Autowired
	private TaskRepository taskRepository;
	@Autowired
	private AgencyOrgRepository orgRepository;
	@Autowired
	private OrderRepository orderRepository;

	@Override
	public Page<TaskOrg> queryOrgMonthRecord(Page<TaskOrg> page) {
		page = taskRepository.queryOrgMonthRecord(page);

		List<TaskOrg> result = Lists.transform(page.getResult(), new Function<TaskOrg, TaskOrg>() {
			@Override
			public TaskOrg apply(TaskOrg input) {
				input.setOrg(orgRepository.get(Long.valueOf(input.getOrgId())));
				return input;
			}
		});

		return page.setResult(result);
	}

	@Override
	public Page<Order> queryOrderMonthRecord(Page<Order> page) {
		page = orderRepository.queryPage(page);
		page.setResult(setOrgId(page.getResult()));
		return page;
	}

	private List<Order> setOrgId(List<Order> result) {
		List<Order> orders = Lists.newArrayList();
		for(Order o : result) {
			AgencyOrg org = orgRepository.queryOrgByFansUserId(o.getWeixinUserId());
			if(null != org) {
				o.setOrgId(org.getId());
			}
			orders.add(o);
		}
		return orders;
	}

	@Override
	public TaskOrg queryByOrgAndMonth(String id, String recordTime) {
		return taskRepository.queryByOrgAndMonth(id, recordTime);
	}

	@Override
	public void update(TaskOrg task) {
		taskRepository.update(task);
	}

	@Override
	public List<Order> query() {
		List<Order> result = orderRepository.query();
		result = setOrgId(result);
		return result;

	}

	@Override
	public List<Order> queryByMonth(String month) {
		List<Order> result = orderRepository.queryByMonth(month);
		result = setOrgId(result);
		return result;
	}

}
